package com.zhangjianling.premp.server.sys.impl;

import com.zhangjianling.premp.dao.sys.SysLogDao;
import com.zhangjianling.premp.entity.sys.SysLog;
import com.zhangjianling.premp.server.sys.SysLogService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class SysLogServiceImpl implements SysLogService {
	@Resource
	private SysLogDao sysLogDao;
	@Override
	public SysLog save(SysLog sysLog) {
		return sysLogDao.save(sysLog);
	}
	@Override
	public Page<SysLog> pageList(int pageNumber, int pageSize, String sortColom, final SysLog log) throws SocketException {
		Pageable pageable = new PageRequest(pageNumber-1, pageSize, Sort.Direction.DESC,sortColom); 
		Page<SysLog> sysLog = sysLogDao.findAll(new Specification<SysLog>(){  
	            @Override  
	            public Predicate toPredicate(Root<SysLog> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {  
	            	 List<Predicate> list = new ArrayList<Predicate>();  
	                 if(StringUtils.isNotBlank(log.getType())){  
	                     list.add(criteriaBuilder.equal(root.get("type").as(String.class),log.getType()));  
	                 }  
	                 if(StringUtils.isNotBlank(log.getCreateDate())){  
	                     list.add(criteriaBuilder.like(root.get("createDate").as(String.class),log.getCreateDate()+"%"));  
	                 }  
	                 Predicate[] p = new Predicate[list.size()];  
	                 return criteriaBuilder.and(list.toArray(p));
	            }  
	        },pageable); 
		 return sysLog;
	}

	@Override
	public SysLog findLog(String id) {
		return sysLogDao.findById(id).get();
	}


}
